import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/userStore";
import router from "@/router";

var request = axios.create({
  baseURL:'https://localhost:50053/api',
  timeout:50000
})

//  请求拦截器
request.interceptors.request.use(config=>{
  // 1 从 pinia中获取token
  const useStore = useUserStore()

  // 2 请求携带token
  const token = useStore.userTokenInfo.token
  if(token){
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
},e=>Promise.reject(e))

// 响应拦截器
request.interceptors.response.use(res=>{
  // console.log(res.data)
  const {data,success,message} = res.data
  if(success){
    return data
  }else{
    ElMessage.warning(message)
    return Promise.reject(new Error(message))
  }
},e=>{
  console.dir(e)
  const useStore = useUserStore()
  if(e.response.status===401){
    const msg = e.response.data.message
    ElMessage.warning(msg)
    useStore.clearUserInfo()
    router.replace('/login')
    return false
  }
  ElMessage.error(e.message)
  return Promise.reject(e)
})

export default request